package nobnak.study.gl.projection;

import android.graphics.Bitmap;


public class Cube {
	public static final float[] NORMALIZED_VERTICES = new float[] {
		-1f, -1f, -1f, 1f,
		-1f, -1f,  1f, 1f,
		-1f,  1f, -1f, 1f,
		-1f,  1f,  1f, 1f,
		
		 1f, -1f, -1f, 1f,
		 1f, -1f,  1f, 1f,
		 1f,  1f, -1f, 1f,
		 1f,  1f,  1f, 1f
	};
	public static final float[] NORMALIZED_UV = new float[] {
		0, 0,
		0, 1, 
		1, 0,
		1, 1
	};
	public static final int[] VERTEX_INDICES = new int[] {
		2, 0, 1, 2, 1, 3,
		3, 1, 5, 3, 5, 7,
		7, 5, 4, 7, 4, 6,
		6, 4, 0, 6, 0, 2,
		2, 3, 7, 2, 7, 6,
		1, 4, 0, 1, 0, 5
	};
	public static final int[] UV_INDIECES = new int[] {
		2, 0, 1, 2, 1, 3,
		2, 0, 1, 2, 1, 3,
		2, 0, 1, 2, 1, 3,
		2, 0, 1, 2, 1, 3,
		2, 0, 1, 2, 1, 3,
		2, 0, 1, 2, 1, 3
	};


	public final float[] modelWorldMatrix;
	public final Bitmap[] textures;
	
	public Cube(float[] modelWorldMatrix, Bitmap[] textures) {
		this.modelWorldMatrix = modelWorldMatrix;
		this.textures = textures;
	}
	
	public Triangle[] tessellate() {
		Triangle[] result = new Triangle[6 * 2];
		for (int iTriangle = 0; iTriangle < result.length; iTriangle++) {
			result[iTriangle] = makeTriangle(iTriangle);
		}
		return result;
	}

	private Triangle makeTriangle(int iTriangle) {
		float[] vertices = new float[Triangle.VERTEX_DIMENSION * Triangle.TRIANGLE_VERTICES_COUNT];
		float[] uv = new float[Triangle.UV_DIMENSION * Triangle.TRIANGLE_VERTICES_COUNT];
		int indexOffset = iTriangle * Triangle.TRIANGLE_VERTICES_COUNT;
		for (int j = 0; j < Triangle.TRIANGLE_VERTICES_COUNT; j++) {
			int indexVertex = VERTEX_INDICES[indexOffset + j] * Triangle.VERTEX_DIMENSION;
			int indexUv = UV_INDIECES[indexOffset + j] * Triangle.UV_DIMENSION;
			setPositionOnVertex(vertices, j * Triangle.VERTEX_DIMENSION, indexVertex);
			setUvOnVertex(uv, j * Triangle.UV_DIMENSION, indexUv);
		}
		Bitmap texture = textures[iTriangle / 2];
		Triangle t = new Triangle(vertices, uv, texture);
		return t;
	}
	private void setPositionOnVertex(float[] vertices, int offset, int vertexOffset) {
		for (int i = 0; i < Triangle.VERTEX_DIMENSION; i++)
			vertices[offset++] = NORMALIZED_VERTICES[vertexOffset++];
	}
	private void setUvOnVertex(float[] uv, int offset, int uvOffset) {
		for (int i = 0; i < Triangle.UV_DIMENSION; i++)
			uv[offset++] = NORMALIZED_UV[uvOffset++];
	}

}
